package com.lyp.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyp.lease.common.exception.LeaseException;
import com.lyp.lease.common.result.ResultCodeEnum;
import com.lyp.lease.model.entity.*;
import com.lyp.lease.model.enums.ItemType;
import com.lyp.lease.web.admin.mapper.*;
import com.lyp.lease.web.admin.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyp.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.lyp.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.lyp.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.lyp.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.lyp.lease.web.admin.vo.fee.FeeValueVo;
import com.lyp.lease.web.admin.vo.graph.GraphVo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    @Autowired
    ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    GraphInfoService graphInfoService;
    @Autowired
    ApartmentFacilityService apartmentFacilityService;
    @Autowired
    ApartmentLabelService apartmentLabelService;
    @Autowired
    ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    GraphInfoMapper graphInfoMapper;
    @Autowired
    LabelInfoMapper labelInfoMapper;
    @Autowired
    FacilityInfoMapper facilityInfoMapper;
    @Autowired
    FeeValueMapper feeValueMapper;
    @Autowired
    ProvinceInfoMapper provinceInfoMapper;
    @Autowired
    CityInfoMapper cityInfoMapper;
    @Autowired
    DistrictInfoMapper districtInfoMapper;
    @Autowired
    RoomInfoMapper roomInfoMapper;



    /**
     *
     * @param apartmentSubmitVo
     */
    @Transactional
    @Override
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {

        boolean isUpdate = apartmentSubmitVo.getId()!=null;
        // 因为前端只传id，先根据id查出对应名字，再赋值给Vo插入到公寓信息表中
        String provinceName = provinceInfoMapper.selectById(apartmentSubmitVo.getProvinceId()).getName();
        String cityName = cityInfoMapper.selectById(apartmentSubmitVo.getCityId()).getName();
        String districtName = districtInfoMapper.selectById(apartmentSubmitVo.getDistrictId()).getName();

        apartmentSubmitVo.setProvinceName(provinceName);
        apartmentSubmitVo.setCityName(cityName);
        apartmentSubmitVo.setDistrictName(districtName);

        super.saveOrUpdate(apartmentSubmitVo); // super是ServiceImpl, 因为本类 extends ServiceImpl

        // 将来根据多表查询将当前公寓对应的信息回显给前端页面，用户修改完需要保存，如果不将之前的删除那数据就重复了
        if (isUpdate) {
            // 删除当前公寓的所有图片
            LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType,ItemType.APARTMENT);
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, apartmentSubmitVo.getId());
            graphInfoService.remove(graphInfoLambdaQueryWrapper);


            // 删除当前公寓的所有配套信息
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId());
            apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

            // 删除当前公寓的所有标签
            LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, apartmentSubmitVo.getId());
            apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);

            // 删除当前公寓所有杂费值
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
        }

        // 插入图片列表
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        for (GraphVo graphVo : graphVoList) {
            GraphInfo graphInfo = new GraphInfo();
            graphInfo.setItemType(ItemType.APARTMENT);
            graphInfo.setItemId(apartmentSubmitVo.getId());
            graphInfo.setName(graphVo.getName());
            graphInfo.setUrl(graphVo.getUrl());
            graphInfoService.saveOrUpdate(graphInfo);
        }

        // 2.公寓添加配套：操作的是公寓_配套中间表，决定这个公寓有什么配套设施
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (!facilityInfoIds.isEmpty()) {
            List<ApartmentFacility> apartmentFacilityList = new ArrayList<>();
            for (Long facilityInfoId : facilityInfoIds) {
                ApartmentFacility apartmentFacility = new ApartmentFacility();
                apartmentFacility.setApartmentId(apartmentSubmitVo.getId());
                apartmentFacility.setFacilityId(facilityInfoId);

                apartmentFacilityList.add(apartmentFacility);

            }
            apartmentFacilityService.saveBatch(apartmentFacilityList);
        }

        //3.插入标签列表，决定当前公寓有什么标签
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (!labelIds.isEmpty()) {
            List<ApartmentLabel> apartmentLabelList = new ArrayList<>();
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel = new ApartmentLabel();
                apartmentLabel.setApartmentId(apartmentSubmitVo.getId());
                apartmentLabel.setLabelId(labelId);
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList);
        }

        //4.插入杂费列表,操作公寓-杂费值中间表，决定了公寓有什么杂费
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!feeValueIds.isEmpty()) {
            List<ApartmentFeeValue> apartmentFeeValueList = new ArrayList<>();
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = new ApartmentFeeValue();
                apartmentFeeValue.setApartmentId(apartmentSubmitVo.getId());
                apartmentFeeValue.setFeeValueId(feeValueId);
                apartmentFeeValueList.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValueList);
        }


    }

    @Override
    public IPage<ApartmentItemVo> pageApartmentItemByQuery(IPage<ApartmentItemVo> apartmentItemVoPage, ApartmentQueryVo queryVo) {

        return apartmentInfoMapper.pageApartmentItemByQuery(apartmentItemVoPage,queryVo);
    }

    @Override
    public ApartmentDetailVo getApartmentDetailById(Long id) {
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        // 查询公寓信息
        ApartmentInfo apartmentInfo = super.getById(id);
        // 查询公寓的所有图片
        // method1
        List<GraphVo> graphVoList = graphInfoMapper.selectListByItemTypeAndId(ItemType.APARTMENT,id);

        // method2
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType,ItemType.APARTMENT);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,id);
        List<GraphInfo> graphInfoList = graphInfoMapper.selectList(graphInfoLambdaQueryWrapper);
        List<GraphVo> graphVoList2 = graphInfoList.stream().map(graphInfo -> {
            GraphVo graphVo = new GraphVo();
            BeanUtils.copyProperties(graphInfo, graphVo);
            return graphVo;
        }).collect(Collectors.toList());


        // 查询公寓的所有标签
        List<LabelInfo> labeInfolList = labelInfoMapper.selectListByApartmentId(id);
        // 查询公寓的所有配套设施
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectListByApartmentId(id);
        // 查询公寓的所有杂费
        List<FeeValueVo> feeValueVoList = feeValueMapper.selectListByApartmentId(id);

        // 将查询的信息封装成apartmentDetailVo对象返回
        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);
        apartmentDetailVo.setGraphVoList(graphVoList);
        apartmentDetailVo.setLabelInfoList(labeInfolList);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);

        return apartmentDetailVo;
    }

    @Override
    public void removeApartmentById(Long id) {

        // 先根据公寓id查询这个公寓的房间数，有房间数就抛异常给全局异常捕获
        LambdaQueryWrapper<RoomInfo> roomInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomInfoLambdaQueryWrapper.eq(RoomInfo::getApartmentId,id);
        Long roomCount = roomInfoMapper.selectCount(roomInfoLambdaQueryWrapper);
        if (roomCount > 0) {
            // 抛出自定义异常，删除异常
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        // 1.删除公寓的所有图片，操作图片表graphInfo
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType,ItemType.APARTMENT);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,id);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);
        // 2.删除公寓的所有标签，操作中间表apartment_label
        LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,id);
        apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);
        // 3.删除公寓的所有设施，操作中间表apartment_facility
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
        // 4.删除公寓的所有杂费值，操作apartment_fee_value
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,id);
        apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);

        // 5.最后删除公寓 apartment_info
        // 或者用apartmentInfoMapper.deleteById(id);
        super.removeById(id);

    }
}




